package com.pig.easy.bpm.mysql.reister;

import com.pig.easy.bpm.mysql.annotation.EnableMysql;
import com.pig.easy.bpm.mysql.aspet.DynamicDataSourceAspect;
import com.pig.easy.bpm.mysql.config.DynamicDataSourceConfiguration;
import com.pig.easy.bpm.mysql.config.MyBatisPlusConfiguration;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.List;

/**
 * todo:
 *
 * @author : pig
 * @date : 2020/5/9 10:34
 */
public class DynamicDataSourceRegister implements ImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableMysql.class.getName()));
        if (null != attributes) {
            Object object = attributes.get("dataSource");
            List<String> dataSourceList = new ArrayList<>();
            if(object.getClass().getName().equals("java.lang.String")){
                dataSourceList.add((String) object);
            } else {
                dataSourceList.addAll((List<String>) object);
            }

            for (String dataSourceEnum : dataSourceList) {
                DynamicDataSourceContextHolder.dataSourceIds.add(dataSourceEnum);
            }
        }
        DynamicDataSourceContextHolder.dataSourceIds.add("common");
        return new String[] {DynamicDataSourceAspect.class.getName(),DynamicDataSourceConfiguration.class.getName(),MyBatisPlusConfiguration.class.getName()};
    }
}
